// 根据最底层路由返回其所有父级路由
export const findParentByPath = (data: any, targetPath: string) => {
    let result: any = [];

    function traverse(data: any, path: any = []) {
        for (let route of data) {
            const currentPath = [...path, route.path];
            if (route.path === targetPath) {
                result = currentPath;
                return true;
            }
            if (route.children && traverse(route.children, currentPath)) {
                return true;
            }
        }
        return false;
    }

    traverse(data);
    return result;
}

// 根据路由路径匹配名称
export const findNameByPath = (data: any, targetPath: string) => {
    for (const item of data) {
        if (item.path === targetPath) {
            return item.name;
        } else if (item.children) {
            const foundName: any = findNameByPath(item.children, targetPath);
            if (foundName) {
                return foundName;
            }
        }
    }
    return null;
}

// 根据路由路径匹配icon
export const findIconByPath = (data: any, targetPath: string) => {
    for (const item of data) {
        if (item.path === targetPath) {
            return item.icon;
        } else if (item.children) {
            const foundIcon: any = findIconByPath(item.children, targetPath);
            if (foundIcon) {
                return foundIcon;
            }
        }
    }
    return null;
}

// 根据路由路径匹配对应组件
export const findElementByPath = (data: any, targetPath: string) => {
    for (const item of data) {
        if (item.path === targetPath) {
            return item.element;
        } else if (item.children) {
            const element: any = findElementByPath(item.children, targetPath);
            if (element) {
                return element;
            }
        }
    }
    return null;
}

// 将路由输出为menu格式
export function transformRoute(data: any) {
    const localData = JSON.parse(localStorage.getItem('auth') as string);
    const userRole = localData ? localData.role : "";
    return data
        .filter((item: any) => item.isShow !== false && (item.roles === undefined || item.roles.includes(userRole))) // 过滤掉 isShow 为 false 的项
        .map((item: any) => {
            const outputItem = {
                key: item.path,
                label: item.name,
                icon: item.icon,
                children: item.children
            };

            if (item.children) {
                outputItem.children = transformRoute(item.children);
            }
            return outputItem;
        });
}